# coding:utf-8
class TrafficStrategy < ActiveRecord::Base
  has_paper_trail :version => :paper_trail_version, :versions => :paper_trail_versions
  belongs_to :terminal_group
  belongs_to :account_group
  attr_accessible :terminal_group_id, :account_group_id, :duration_total, :limit_down, :limit_up, :traffic_total, :times, :status, :name, :beaut_traffic_total
  validates :duration_total, :traffic_total, :limit_down, :limit_up, :times, presence: true
  validates :times, numericality: { only_integer: true, greater_than_or_equal_to: 1 }
  validates :duration_total,:traffic_total,:limit_down,:limit_up, numericality: { only_integer: true, greater_than_or_equal_to: -1 }
  validates_each :traffic_total do |record, attr, value|
    unless value == -1 || record.duration_total == -1
      record.errors.add(attr, '总流量和总时长，至少有一个为-1')
    end
  end

  # no where option for rails 3.2,only rails 4 has
  #validates_uniqueness_of :terminal_group_id, scope: :account_group_id, if: Proc.new { |user| !!user.status }
  scope :is_on, -> { where(status: true)}
  scope :by_terminal_group, lambda {|tg| where(["terminal_group_id = ? or terminal_group_id is null",tg]) }
  scope :by_city, lambda {|city| joins(:terminal_group).where(["terminal_groups.city_id = ? or terminal_group_id is null",city])}

  validate :terminal_group_must_be_uniq

  attr_accessor :beaut_traffic_total

  def beaut_traffic_total
    if self.traffic_total == -1
      self.traffic_total
    else
      self.traffic_total/(1024**2)
    end
  end

  def beaut_traffic_total=(btt)
    if btt.to_i == -1
      self.traffic_total = -1
    else
      self.traffic_total = btt.to_i*(1024**2)
    end
  end

  def display_in_tree
    "#{self.terminal_group.try(:group_name)} #{self.account_group.try(:group_name)}"
  end

  after_initialize :init

  def init
    self.status = true if self.status.nil?
    self.duration_total = -1 if self.duration_total.nil?
    self.traffic_total = -1 if self.traffic_total.nil?
    self.limit_down = -1 if self.limit_down.nil?
    self.limit_up = -1 if self.limit_up.nil?
  end

  def promotion_info?
    self.errors.size == 1 && self.errors[:terminal_group_id] == ["已经被使用"]
  end

  def cover_using_strategy
    begin
      TrafficStrategy.transaction do |variable|
        old_strategy = TrafficStrategy.where(terminal_group_id: self.terminal_group_id,
          account_group_id: self.account_group_id,
          status: true)
        logger.info self.new_record?
        old_strategy.where("id != #{self.id}") unless self.new_record?
        old_strategy.first.destroy if old_strategy.present?
        self.save   
      end
    rescue => e
      logger.info e
      false
    end
  end

  private

  def terminal_group_must_be_uniq
    if !!self.status
      error_flag = if self.new_record?
        TrafficStrategy.exists?(terminal_group_id: self.terminal_group_id,account_group_id: self.account_group_id,status: true)
      else
        ts = TrafficStrategy.where(terminal_group_id: self.terminal_group_id,account_group_id: self.account_group_id,status: true).first
        ts && ts.id != self.id
      end
      errors[:terminal_group_id] << "已经被使用" if error_flag
    end
  end

end
